<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
	/**
	 * Authenticates a user.
	 * The example implementation makes sure if the username and password
	 * are both 'demo'.
	 * In practical applications, this should be changed to authenticate
	 * against some persistent user identity storage (e.g. database).
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
		$utilisateurs=array(
			'demo'=>'demo',
			'admin'=>'admin',
		);
		
		$allPersonnels = new PERSONNELTECHNIQUE;
		$personnels = $allPersonnels->findAll();
		$personnels = CHtml::listData($personnels, 'LOGIN_PERSONNEL', 'PASSWORD_PERSONNEL');
		
		$allEmetteurs = new EMETTEUR;
		$emetteurs = $allEmetteurs->findAll();
		$emetteurs = CHtml::listData($emetteurs, 'LOGIN_EMETTEUR', 'PASSWORD_EMETTEUR');
		
		if(isset($utilisateurs[$this->username]))
		{
			if($utilisateurs[$this->username] == $this->password)
			{
				Yii::app()->user->setState('role', 1);
				$this->errorCode=self::ERROR_NONE;
			}
			else
				$this->errorCode=self::ERROR_PASSWORD_INVALID;
		}
		else if(isset($personnels[$this->username]))
		{
			$allPersonnels = new PERSONNELTECHNIQUE;
			$responsable = $allPersonnels->findByAttributes(array('FONCTION_PERSONNEL'=>'Chef de service'));
		
			if($personnels[$this->username] == $this->password)
			{
				if($this->username == $responsable['LOGIN_PERSONNEL'])
					Yii::app()->user->setState('role', 4);
				else
					Yii::app()->user->setState('role', 3);
					
				$this->errorCode=self::ERROR_NONE;
			}
			else
				$this->errorCode=self::ERROR_PASSWORD_INVALID;
		}
		else if(isset($emetteurs[$this->username]))
		{
			if($emetteurs[$this->username] == $this->password)
			{
				Yii::app()->user->setState('role', 2);
				$this->errorCode=self::ERROR_NONE;
			}
			else
				$this->errorCode=self::ERROR_PASSWORD_INVALID;
		}
		else
			$this->errorCode=self::ERROR_USERNAME_INVALID;

		return !$this->errorCode;
	}
}